package com.lechi.web.util;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.io.*;

/**
 * The type Object to byte buf converter.
 */
public class ObjectToByteBufConverter {

    /**
     * To byte buf byte buf.
     *
     * @param object the object
     * @return the byte buf
     * @throws IOException the io exception
     */
    public static ByteBuf toByteBuf(Object object) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(object);
        oos.flush();
        return Unpooled.wrappedBuffer(bos.toByteArray());
    }

    /**
     * From byte buf object.
     *
     * @param buf the buf
     * @return the object
     * @throws IOException            the io exception
     * @throws ClassNotFoundException the class not found exception
     */
    public static Object fromByteBuf(ByteBuf buf) throws IOException, ClassNotFoundException {
        ByteArrayInputStream bis = new ByteArrayInputStream(buf.array());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return ois.readObject();
    }

    /**
     * The entry point of application.
     *
     * @param args the input arguments
     * @throws IOException            the io exception
     * @throws ClassNotFoundException the class not found exception
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 示例对象
        MyObject myObject = new MyObject(1, "example");

        // 序列化
        ByteBuf byteBuf = toByteBuf(myObject);

        // 反序列化
        MyObject deserializedObject = (MyObject) fromByteBuf(byteBuf);
        System.out.println(deserializedObject.getId()); // 输出: 1
        System.out.println(deserializedObject.getName()); // 输出: example
    }
}

/**
 * The type My object.
 */
class MyObject implements Serializable {
    private int id;
    private String name;

    /**
     * Instantiates a new My object.
     *
     * @param id   the id
     * @param name the name
     */
    public MyObject(int id, String name) {
        this.id = id;
        this.name = name;
    }

    /**
     * Gets id.
     *
     * @return the id
     */
// getters and setters
    public int getId() {
        return id;
    }

    /**
     * Sets id.
     *
     * @param id the id
     */
    public void setId(int id) {
        this.id = id;
    }

    /**
     * Gets name.
     *
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * Sets name.
     *
     * @param name the name
     */
    public void setName(String name) {
        this.name = name;
    }
}